# gozerplugs/gozernet.py
#
#

## gozerbot imports

from gozerbot.callbacks import callbacks, jcallbacks, gn_callbacks
from gozerbot.persist.persist import PlugPersist
from gozerbot.commands import cmnds
from gozerbot.examples import examples
from gozerbot.irc.monitor import outmonitor
from gozerbot.persist.persistconfig import PersistConfig
from gozerbot.eventbase import EventBase
from gozerbot.utils.exception import handle_exception
from gozerbot.utils.log import rlog
from gozerbot.utils.textutils import html_unescape
from gozerbot.xmpp.bot import Bot
from gozerbot.fleet import fleet
from gozerbot.gozernet.event import RemoteEvent
from gozerbot.gozernet.bot import GozerNetBot
from gozerbot.aliases import aliasset

## simplejson imports

from simplejson import dumps

## basic imports

import socket
import re
import copy

cpy = copy.deepcopy

## VARS

outjid = "relay@gzrbot.appspotchat.com"
state = PlugPersist('gozernet')

if not state.data:
    state.data = {}

if not state.data.has_key('out'):
    state.data['out'] = [outjid, ]

if not state.data.has_key('forward'):
    state.data['forward'] = []

## callbacks

def preremote(bot, event):

    return True

def handle_doremote(bot, event):

    if not event.channel in state.data['forward']:
        return

    rlog(10, 'gozernet', "out - %s - %s - %s - %s (%s)" % (state.data['out'], event.channel, event.userhost, event.txt, event.cbtype))

    for out in state.data['out']:

        try:
             (source, printto) = out
        except ValueError:
             source = ""
             printto = out

        if source != bot.name:
             continue

        outbot = fleet.byname('gozernet')
         
        if not outbot:
            raise Exception("can't find 'gozernet' bot in fleet")

        try:
            outbot.say(printto, event.txt, event, groupchat=False)
        except Exception, ex:
            handle_exception()

callbacks.add('PRIVMSG', handle_doremote, preremote, threaded=True)
outmonitor.add('gozernet', handle_doremote, preremote, threaded=True)

def handle_jabberin(bot, event):

    try:
        e = RemoteEvent()

        if event.txt.startswith('{'):
            e.parse(bot, event)
        else:
            return

    except Exception, ex:
        handle_exception()
        print event.txt
        return

    #rlog(10, bot.name, 'gozernet - in - %s - %s (%s) ' % (e.userhost, e.txt, e.cbtype))

    bot.doevent(e)
    
jcallbacks.add('Message', handle_jabberin, threaded=True)

def handle_gozernet_addout(bot, event):

    global state

    if not event.rest:
        event.missing('<JID>')
        return

    if not [bot.name, event.rest] in state.data['out']:
        state.data['out'].append([bot.name, event.rest])
        state.save()

    event.done()

cmnds.add('gozernet-addout', handle_gozernet_addout, 'OPER')

def handle_gozernet_delout(bot, event):

    global state

    if not event.rest:
        event.missing('<JID>')
        return

    try:
        state.data['out'].remove([bot.name, event.rest])
        state.save()
    except ValueError:
        try:
            state.data['out'].remove(event.rest)
        except ValueError:
            pass

    event.done()

cmnds.add('gozernet-delout', handle_gozernet_delout, 'OPER')

def handle_gozernet_outs(bot, event):
    event.reply(state.data['out'])

cmnds.add('gozernet-outs', handle_gozernet_outs, 'OPER')

def handle_gozernetforward(bot, event):

    if not event.args:
        event.missing('<channel>')
        return

    state.data['forward'].append(event.args[0])
    state.save()
    event.done()

cmnds.add('gozernet-forward', handle_gozernetforward, 'OPER')
examples.add('gozernet-forward', 'add a forward item so that channels matching this get send over the gozernet', 'gozernet-forward #dunkbots')

def handle_gozernetdelforward(bot, event):

    if not event.args:
        event.missing('<channel>')
        return

    try:
        state.data['forward'].remove(event.args[0])
        state.save()
        event.done()
    except ValueError:
        event.reply("we are not forwarding %s" % event.args[0])

cmnds.add('gozernet-delforward', handle_gozernetdelforward, 'OPER')
examples.add('gozernet-delforward', 'remove a forward item so that channels matching this no longer get send over the gozernet', 'gozernet-delforward #dunkbots')

def handle_gozernetlistforward(bot, event):
    event.reply("gozernet forwards: ", state.data['forward'])

cmnds.add('gozernet-listforward', handle_gozernetlistforward, 'OPER')
examples.add('gozernet-listforward', 'show gozernet forwards', 'gozernet-listforwards')


def handle_gozernetcmnd(bot, event):

    cmndstring = event.rest

    if not cmndstring:
        event.missing("<cmnd>")
        return

    gnbot = fleet.byname('gozernet')

    if gnbot:
        gnbot.cmnd(state.data['out'], "!%s" % cmndstring, event)
        event.reply("sent to: ", state.data['out'])
    else:
        event.reply("can't find 'gozernet' bot in fleet")

cmnds.add('gozernet-cmnd', handle_gozernetcmnd, 'OPER')
examples.add('gozernet-cmnd', 'execute a command on the gozernet', 'gozernet-cmnd version')
aliasset('gn', 'gozernet-cmnd')
